package com.sheep.taobao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.json.JSONArray;
import org.json.JSONObject;

public class WomenDressDao {
	
	public void insertBatch(String jsonStr) throws Exception {
		JSONObject jsonObj = new JSONObject(jsonStr);
		JSONObject rootObj = (JSONObject)jsonObj.get("taobaoke_items_coupon_get_response");
		JSONObject items = (JSONObject)rootObj.get("taobaoke_items");
		JSONArray allItem = (JSONArray)items.get("taobaoke_item");
		
		Connection conn=null;
		PreparedStatement pstmtInsert=null;
		String sql = "INSERT INTO product(name, imgUrl, yn, price, createdate, updatedate) VALUES(?, ?, 0, ?, NOW(), NOW())";
		try {
			conn=JdbcUtil.getConnection();
			conn.setAutoCommit(false);
			pstmtInsert=conn.prepareStatement(sql);
			for(int i=0; i<allItem.length(); i++ ) {
				Long tbNumId = (Long)allItem.getJSONObject(i).get("num_iid");
				String productName = (String)allItem.getJSONObject(i).get("title");
				String imgUrl = (String)allItem.getJSONObject(i).get("pic_url");
				String price = (String)allItem.getJSONObject(i).get("price");
				
				pstmtInsert.setString(1, productName);
				pstmtInsert.setString(2, imgUrl);
				pstmtInsert.setFloat(3, Float.parseFloat(price));
			}
			pstmtInsert.executeBatch();
			conn.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.close(null, pstmtInsert, null);
		}
		
	}
	
	public static void main(String[] args) throws Exception {
		String jsonStr = "{\"taobaoke_items_coupon_get_response\": {\"taobaoke_items\": {\"taobaoke_item\": [{\"num_iid\": 22656144753,\"pic_url\": \"http://img03.taobaocdn.com/bao/uploaded/i3/16605028084793843/T1t.W7FXFbXXXXXXXX_!!0-item_pic.jpg\",\"price\": \"256.00\",\"title\": \"【天天特价】2013秋冬装哥弟阿玛施正品开衫 <span class=H>羊绒</span>针织衫毛衣 厚款\"},{\"num_iid\": 19995134968,\"pic_url\": \"http://img01.taobaocdn.com/bao/uploaded/i1/11910030409275747/T1dl_dFn0dXXXXXXXX_!!0-item_pic.jpg\",\"price\": \"1680.00\",\"title\": \"【天天特价】哥弟正品女装2013女士<span class=H>羊绒</span>衫中长款长袖毛衣打底衫\"},{\"num_iid\": 17312191423,\"pic_url\": \"http://img01.taobaocdn.com/bao/uploaded/i1/19110041375844232/T1paPrFnNcXXXXXXXX_!!0-item_pic.jpg\",\"price\": \"1200.00\",\"title\": \"【天天特价】新款大码显瘦手工钉珠 羊毛<span class=H>羊绒</span>秋冬连衣裙打底裙子\"},{\"num_iid\": 35056584023,\"pic_url\": \"http://img01.taobaocdn.com/bao/uploaded/i1/18029028807736631/T1X1m7FmFiXXXXXXXX_!!0-item_pic.jpg\",\"price\": \"388.00\",\"title\": \"【天天特价】2013女装秋冬修身显瘦<span class=H>羊绒</span>衫圆领短款打底衫韩版毛衣\"},{\"num_iid\": 22327947149,\"pic_url\": \"http://img02.taobaocdn.com/bao/uploaded/i2/19956029244383420/T1066dFnVgXXXXXXXX_!!0-item_pic.jpg\",\"price\": \"286.00\",\"title\": \"【天天特价】女装新款秋装女式阿卡V领灯笼袖<span class=H>羊绒</span>衫上衣打底衫\"}]},\"total_results\": 503724}}";
		WomenDressDao dao = new WomenDressDao();
		dao.insertBatch(jsonStr);
	}
}
